<template>
  <div class="home" id="o2">
    <div class="user-list">
      <div class="user-online-num">当前在线人数： {{onlineNum}}</div>
      <input class="name-input" v-model="nickName" placeholder="请输入昵称"/>
      <button class="input-send-btn" style="margin-bottom:10px" @click="changeNickName">确认昵称</button>
      <el-divider class="divider">online</el-divider>
      <div class="user-block" v-for="(user, index) in userList" :key="index">{{user.name}}</div>

    </div>
    <div class="chat-block">
      <div class="chat-history" >
        <div  class="chat-history-content" id="chat-history" ref="chat_history">
          <div class="history-block" v-for="(item, index) in historyList" :key="index" :id="getId(index)">
            <div class="history-name">{{item.name}}：</div>
            <div class="history-content" >{{item.content}}</div>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <el-input class="input-content" type="textarea" resize="none" :autosize="{ minRows: 3, maxRows: 3}" placeholder="请输入内容" v-model="msg"></el-input>
        <!-- <textarea class="input-content"  v-model="msg" rows="3" cols="20"></textarea> -->
        <!-- <el-button class="input-send-btn" @click="send">发送</el-button> -->
        <button class="send-btn" @click="send">发送</button>
        <!-- <el-button class="input-send-btn" @click="tset_setData">setData</el-button>
        <el-button class="input-send-btn" @click="test_getData">getData</el-button> -->
      </div>
    </div>
  </div>
</template>

<script>
// import axios from 'axios';
export default {
  name: 'HelloWorld',
  data () {
    return {
      onlineNum: "loading",
      ip:'192.168.1.1',
      url:'url',
      nickName:'',
      msg:'',
      userList:[],
      historyList:[
      ]
    }
  },
  mounted () {
    let that = this
    chrome.tabs.query(
      {active: true, currentWindow: true},
      function (tabs) {
        var port = chrome.tabs.connect(//建立通道
            tabs[0].id,
            {name: "queryUrl"}//通道名称
        );
        port.postMessage({url: ""});//向通道中发送消息
        port.onMessage.addListener(function (msg) {//这里同时利用通道建立监听消息，可以监听对方返回的消息
            console.log("接收到url: ", msg.url)
            that.url = msg.url
        });
    });

    // //设置滚动条    
    // let msg = document.getElementById('chat-history') // 获取对象
    // msg.scrollTop = msg.scrollHeight // 滚动高度

    //读取缓存数据
    this.readData()

    //读取历史消息记录
    this.PostMsg("getHistory", "", function(msg){
      // console.log("取得history: ", msg)
    })

    //设置消息监听
    // let that = this
    chrome.runtime.onMessage.addListener((req,sender, sendResponse) => {
      console.log('接收了来自 content.js的消息', req.info)
      let res = JSON.parse(req.info)
      //判断消息类型
      switch(res.type){
        case "heartbeat":{
          console.log("处理心跳")
          let receiveMsg = res.data
          that.onlineNum = receiveMsg.length
          that.userList = receiveMsg
          break;
        }
        case "history":{
          console.log("处理聊天", res)
          let receiveMsg = res.data
          for(var i = 0; i < receiveMsg.length; i++){
            var temp = {
              name: receiveMsg[i].user_name,
              content: receiveMsg[i].content
            }
            that.historyList.push(temp)
          }
          window.setTimeout(function(){
            var msgId = "index_"+(that.historyList.length-1)
            var newMsg = document.getElementById(msgId);
            newMsg.scrollIntoView();
          }, 100); 
          break
        }
      }
    }) 
  },

  computed: {
    defaultText () {
      return browser.i18n.getMessage('extName')
    }
  },
  methods:{
    getId(id){
      return "index_"+id
    },
    tset_setData(){

      //与backgroundJS通讯  
      // var msg = await browser.runtime.sendMessage({method: "login"})

      // //与contentJS通讯    
      // this.PostMsg("channelName", {id: 1, name: "张大力"}, function(msg){
      //   console.log("msg: ", msg)
      // })

      // //缓存处理        
      // chrome.storage.local.set({"ahaha": "hihihi"});
      // chrome.storage.local.get(['ahaha'], function(result) {
      //   console.log('Value currently is ' , result);
      // });
    },
    test_getData(){
      this.PostMsg("create_socket", {id: 1, name: "张大力"}, function(msg){
        console.log("msg: ", msg)
      })
    },
    changeNickName(){
      this.PostMsg("changeNickName", this.nickName, function(msg){
        console.log("msg: ", msg)
      })
      // chrome.storage.local.set({"nickName": this.nickName});
    },
    send(){      
      console.log("发送！msg: ", this.msg)
      this.PostMsg("sendMsg", this.msg, function(msg){
        console.log("发送消息的返回: ", msg)
      })
      this.msg = ""
    },
    PostMsg(channelName, params, callbackFunc){
      chrome.tabs.query(
        {active: true, currentWindow: true},
        function (tabs) {
            var port = chrome.tabs.connect(//建立通道
                tabs[0].id,
                {name: channelName}//通道名称
            );
            port.postMessage(params);//向通道中发送消息
            port.onMessage.addListener(callbackFunc);
        });
    },
    async dealNickName(name){
      if(name.length >0){
        return name
      }
      //如果没有，说明缓存里也没有，那就随机一个新的
      name = '热心网友' + Math.round(Math.random()*10000)
      await this.setStorage('nickName', name)
      this.nickName = name
      return name
    },
    async readData(){
      //昵称
      let that = this
      chrome.storage.local.get(['nickName'], function(result) {
        console.log('Value currently is ' , result);
        console.log("获取昵称缓存 ", result['nickName'])
        if(result['nickName'].length>0){
          that.nickName = result['nickName']
        }else{
          that.nickName = ''
        }
      });
    },
    async setStorage(key, value){
      chrome.tabs.query(
        {active: true, currentWindow: true},
        function (tabs) {
          var port = chrome.tabs.connect(//建立通道
              tabs[0].id,
              {name: "setData"}//通道名称
          );
          port.postMessage({key: key, value: value});//向通道中发送消息
          port.onMessage.addListener(function (msg) {//这里同时利用通道建立监听消息，可以监听对方返回的消息
            console.log("接受到setData返回 msg: ", msg)
              if(msg.code == 0){
                  console.log("缓存完成 key: ", key, " value: ", value)
              };
          });
      });
    },
    async getStorage(key, method){
      let that = this
      chrome.tabs.query(
        {active: true, currentWindow: true},
        function (tabs) {
          var port = chrome.tabs.connect(//建立通道
              tabs[0].id,
              {name: "getData"}//通道名称
          );
          port.postMessage({key: key});//向通道中发送消息
          port.onMessage.addListener(function (msg) {//这里同时利用通道建立监听消息，可以监听对方返回的消息
            console.log("接受到getData返回 msg: ", msg)
            switch(method){
              case 'readData':{
                console.log("更新data ", key, " ", msg.value)
                that[key] = msg.value
                console.log("that.nickName: ", that.nickName)
              }
            }
          });
      });
    }
  }
}
</script>
<style>

.el-textarea__inner{
  /* border: 1px none solid solid none black; */
  border-width: 1px;
  border-style: solid none none none;
  border-color: black;
  border-radius: 0;
}
</style>
<style scoped>
.home {
  display: flex;
  flex-direction: row;
  height: 580px;
}
.user-online-num{  
  margin-top: 10px;
  /* margin-bottom: 10px; */
}
.name-input{
  /* margin: 10px 4px 20px 4px; */
  margin-top: 10px;
  margin-bottom: 5px;
  width: 120px;
  height: 30px;
}
.divider{
  margin-top: 10px;
  margin-bottom: 10px;
}
.user-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 99%;
  width: 30%;
  border-style: solid; 
  border-width:1px;
}
.chat-block {
  display: flex;
  flex-direction: column;
  width: 70%;
  height: 99%;
  border-style: solid solid solid none; 
  border-width:1px;
}
.chat-history {
  width: 99%;
  height: 80%;
  border-style: none none none none; 
  border-width:1px;
}

.chat-history-content {
  width: 100%;
  height: 100%;
  border-style: none none none none; 
  border-width:1px;
  overflow-y: scroll;
}

.chat-input {
  width: 100%;
  height: 20%;
}
.user-block {
  /* margin: 5px 5px; */
  border-style: none none solid none; 
  border-width:1px;
  width: 100%;
  text-indent: 10px;
  margin: 5px 0px;
  line-height: 24px;
  /* margin-left: 10px; */
}
.history-block {
  margin: 5px 5px;
}
.history-content{
  margin: 5px 15px 15px;
  padding: 3px;
  line-height: 20px;
  border-style: solid; 
  border-width:1px;
}
.input-content{ 
  border-width:1px;
 /* border-style: solid;  */
 border-color: black;

}
.input-send-btn{
  width: 125px;
}
.send-btn{
  width: 125px;
  float: right;
  margin-right: 10px;
  margin-top: 10px;
}
::-webkit-scrollbar { 
    display: none; }
</style>
